package main

import (
	"github.com/kardianos/service"
	"github.com/robfig/cron"
	"time"
	"os"
	"log"
	"fmt"
)

//
//import (
//	"github.com/kardianos/service"
//	srv "../daemon/service"
//	"fmt"
//)
//
//func loger() {
//	fmt.Println("log....")
//}
//func main() {
//	cfg := &service.Config{Name: "simple",
//		DisplayName: "a simple service",
//		Description: "This is an example go service",
//	}
//
//	prg := &srv.Program{Run: loger}
//
//	s, err := service.New(prg, cfg)
//}

var logger service.Logger

type program struct {
	Run func()
}

func demo() {
	logInfo(time.Now().String())

}

func CronSetUp() {

	c := cron.New()

	c.AddFunc("*/5 * * * * *", func() {
		demo()

	})

	c.Start()

	t1 := time.NewTimer(time.Second * 10)
	for {
		select {
		case <-t1.C:
			t1.Reset(time.Second * 10)
		}
	}
}

func (p *program) Start(s service.Service) error {
	// Start should not block. Do the actual work async.
	go p.run()
	return nil
}
func (p *program) run() {
	// Do work here
	logInfo("服务运行")
	//Run func()
	p.Run()

}
func (p *program) Stop(s service.Service) error {
	// Stop should not block. Return with a few seconds.
	return nil
}

func logInfo(s string) {
	//创建输出日志文件


	logFile, err := os.OpenFile("./log.txt", os.O_CREATE|os.O_RDWR|os.O_APPEND, os.ModeAppend|os.ModePerm);
	if err != nil {
		fmt.Println(err);
	}

	//创建一个Logger
	//参数1：日志写入目的地
	//参数2：每条日志的前缀
	//参数3：日志属性
	loger := log.New(logFile, "test_", log.Ldate|log.Ltime|log.Lshortfile);

	//Flags返回Logger的输出选项
	fmt.Println(loger.Flags());

	//SetFlags设置输出选项
	loger.SetFlags(log.Ldate | log.Ltime | log.Lshortfile);

	//返回输出前缀
	fmt.Println(loger.Prefix());

	//输出一条日志
	loger.Output(2, s);


}

func main() {

	svcConfig := &service.Config{
		Name:        "xiaohan",
		DisplayName: "Go Service Example",
		Description: "This is an example Go service.",
	}

	prg := &program{Run: CronSetUp}
	ser, err := service.New(prg, svcConfig)
	if err != nil {
		logInfo("生成服务异常")
	}
	ser.Run()
	if len(os.Args) > 1 {
		err = service.Control(ser, os.Args[1])
		if err != nil {
			logger.Error("生成服务异常1", err)
		}
	} else {
		ser.Run()
	}
	logInfo("1")
}
